/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.dao.impl;

import br.com.ecommerce.dao.PromocaoDAO;
import br.com.ecommerce.dao.pojo.EntityPojo;
import br.com.ecommerce.dao.pojo.Promocao;
import br.com.ecommerce.exceptions.DatabaseException;
import br.com.ecommerce.exceptions.IdInvalidoException;
import br.com.ecommerce.exceptions.ObjetoInvalidoException;
import br.com.ecommerce.factory.DatabaseFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Classe que implementa os métodos que manipulam a entidade Promocao
 * @author Afonso
 */
public class PromocaoDAOImpl implements PromocaoDAO {

    @Override
    public void create(EntityPojo obj) throws ObjetoInvalidoException,
            DatabaseException {
        if (obj == null || !(obj instanceof Promocao)) {
           throw new ObjetoInvalidoException("Objeto POJO é null ou "
                   + "não é do tipo Promocao");
        }

        Promocao promocao = (Promocao)obj;
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "insert into PROMOCAO values (PROMOCAO_SEQ.nextval, " +
                    "'" + promocao.getNomePromocao() + "', " +
                    "'" + promocao.getDesconto().toString().replace(".", ",") + "', " +
                    "'" + promocao.getDescricao() + "',"
                    + promocao.getSituacao() + ")";

            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }

    @Override
    public EntityPojo readById(Integer idPrimaryKey) throws IdInvalidoException,
            DatabaseException {
        if (idPrimaryKey == null) {
           throw new IdInvalidoException("ID inválido");

        }

        Promocao promocao = new Promocao();
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;
        try {
            sql = "SELECT * FROM PROMOCAO WHERE ID_PROMOCAO="+idPrimaryKey;

            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                promocao.setIdPrimaryKey(idPrimaryKey);
                promocao.setNomePromocao(rs.getString(2));
                promocao.setDesconto(rs.getFloat(3));
                promocao.setDescricao(rs.getString(4));
                promocao.setSituacao(rs.getInt(5));

            } else {
                 throw new DatabaseException("Não há dados na base de dados para"
                         + " a query: " + sql);

            }
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }

        return promocao;
    }

    @Override
    public List readAll() throws DatabaseException {
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;
        List<Promocao> list = new ArrayList<Promocao>();
        try {
            sql = "SELECT * FROM PROMOCAO ORDER BY ID_PROMOCAO";

            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                Promocao promocao = new Promocao();
                promocao.setIdPrimaryKey(rs.getInt(1));
                promocao.setNomePromocao(rs.getString(2));
                promocao.setDesconto(rs.getFloat(3));
                promocao.setDescricao(rs.getString(4));
                promocao.setSituacao(rs.getInt(5));


              //  Logger.getLogger(ProdutoDAOImpl.class.getName())
              //              .log(Level.INFO, "String SQL : " + produto.toString());

                list.add(promocao);
            }


            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }

        return list;

    }

    /**
     * Para entidades que não podem ter seus registros excluídos, o campo
     * situacao é alterado para o valor 0, indicando que o registro está
     * desativado
     * @param idPrimaryKey
     * @throws IdInvalidoException
     * @throws DatabaseException
     */
    @Override
    public void deleteById(Integer idPrimaryKey) throws IdInvalidoException,
            DatabaseException {
        if (idPrimaryKey == null) {
           throw new IdInvalidoException("ID inválido");

        }

        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "UPDATE PROMOCAO SET SITUACAO=0 "
                    + "WHERE ID_PROMOCAO='" + idPrimaryKey+"'";

            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }

    @Override
    public void update(EntityPojo obj) throws ObjetoInvalidoException, DatabaseException {
        if (obj == null || !(obj instanceof Promocao)) {
           throw new ObjetoInvalidoException("Objeto POJO é null ou "
                   + "não é do tipo Promocao");
        }

        Promocao promocao = (Promocao)obj;
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "UPDATE PROMOCAO SET NOME_PROMOCAO='" +
                    promocao.getNomePromocao() + "', "
                    + "DESCRICAO='" + promocao.getDescricao() + "', "
                    + "DESCONTO='" + promocao.getDesconto().toString().replace(".", ",") + "',"
                    + "SITUACAO=" + promocao.getSituacao()
                    + " WHERE ID_PROMOCAO = " + promocao.getIdPrimaryKey();

            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(PromocaoDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }


}
